<template>
  <div>
    <el-row>
      <el-col class="login-box" :span="8" :offset="8">
        <h1>Mall-Pro-Admin</h1>
        <el-form ref="ruleForm" :model="form" label-width="80px" :rules="rules">
          <el-form-item label="账号" prop="username">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit('ruleForm')">登录</el-button>
            <el-button type="info" @click="onSubmit">忘记密码?</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {login} from '@/api/auth'

export default {
  name: 'Login',
  data () {
    return {
      form: {
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [
          {required: true, message: '请输入用户账号', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入用户密码', trigger: 'change'}
        ]
      }
    }
  },
  methods: {
    onSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.handlerLogin()
        } else {
          return false
        }
      })
    },
    handlerLogin () {
      login(this.form).then(res => {
        const obj = res.data

        this.$store.commit('SET_TOKEN', obj.token)
        this.$store.commit('SET_TOKEN_KEY', obj.tokenHeader)

        this.$message.success('登录成功')
        this.$router.push('/')
      })
    }
  }
}
</script>

<style scoped>

el-button {
  width: 100%;
}

h1 {
  padding-left: 80px;
}

.login-box {
  margin-top: 200px;
}
</style>
